<?
require_once "inc.init.php";

// THE OBJ:
$obj = new portfolio(); // <---- Change this !!!
$obj-> setDbLink($dbLink);

// GETTING:
if ( !$obj->get($_GET[$obj->_dbIndex] ) )
{
    header("Location: index.php");
    die();
}

$messenger = new Messenger();

// SAVING:
if ($_POST['action'] == 'saveField') 
{
    if ($user->isEnabledTo("write", $module->id))
    {
        $objField = new portfolio_table_fields();
        $objField->setDbLink($dbLink);
        $objField->set($_POST, true);
        $objField->portfolioID = $obj->getID();
        $objField->active ='Y';
        $objField->userID_modified = $user->getID();
        
        if($objField->save())
        {
            $messenger->setMessageType(1);
            $messenger->addMessage("Data successfully added.");
        }
        else $messenger->addMessage("Error adding Data.");
    }
}

if($_POST['action']=='orderContent')
{
    if ($user->isEnabledTo("write", $module->id))
    {
        $objField = new portfolio_table_fields();
        $noErrors=false;
        $newOrder = explode('&',$_POST['newOrder']);
        if (is_array($newOrder))
        {
            for($i=0; $i<count($newOrder); $i++)
            {
                $orderedItemID = intval(str_replace('mySortable[]=content_', '', $newOrder[$i]));
                $sql = "UPDATE ".$objField->_dbTable." SET position='". $i ."' WHERE ".$objField->_dbIndex."=".$orderedItemID;
                $noErrors = mysql_query($sql);
                if (!$noErrors) break;
            }
            if ($noErrors)
            {
                $messenger->setMessageType(1);
                $messenger->addMessage("List of items ordered successfully.");
            }
            else $messenger->addMessage("Failed to sort the list of items: ". mysql_error());
        }
    } else $messenger->addMessage($lang->translate("user_action_denied"));
    
    $response["messages"] = $messenger->getArMessages(); 
    $response["success"] = $noErrors; 
    echo json_encode($response);
    exit();
}

if($_GET['action'] == 'deleteField')
{
    if ($user->isEnabledTo("write", $module->id))
    {
        $objField = new portfolio_table_fields();
        $objField->setDbLink($dbLink);
        $_GET[$objField->_dbIndex]? $objField->get((int)$_GET[$objField->_dbIndex]) : null;
        if ($objField->delete())
        {
            $messenger->setMessageType(1);
            $messenger->addMessage("Dato successfully removed");
        }
        else $messenger->addMessage("Failed to delete Dato: ". $messenger->getErrorMessage());
    }
    else $messenger->addMessage($lang->translate("user_action_denied"));
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title><?= $GLOBALS["website"]["name"] ?></title>
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> 
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/bootstrap.css">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/font-awesome.min.css">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/plugin.css">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/font.css" cache="false">
    <link rel="stylesheet" href="<?= $GLOBALS['CONF']['url']['admin']?>/css/style.css">
    <script src="<?= $GLOBALS['CONF']['url']['js'] ?>/lib/prototype-min.js" type="text/javascript" language="javascript" charset="utf-8"></script>
    <?=jquery()?>
    <?=jqueryui()?>
    <script type="text/javascript">
        var $j = jQuery.noConflict();
    </script>
    <script src="<?= $GLOBALS['CONF']['url']['js'] ?>/lib/bootstrap/js/bootstrap.min.js"></script>
    <script language="JavaScript" type="text/javascript" src="<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/tiny_mce/tinymce.min.js"></script>
    <script src="<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/scriptaculous/scriptaculous.js?load=effects,controls,dragdrop" type="text/javascript" language="javascript" charset="utf-8"></script>
    <!-- Needs to be seperate script tags! -->
    <script language="JavaScript" type="text/javascript">
        tinymce.baseURL = "<?= $GLOBALS["CONF"]["url"]["js"] ?>/lib/tiny_mce";
        tinyMCE.init({
            theme: 'modern',
            plugins: [
                "advlist autolink lists link image charmap print preview hr anchor pagebreak",
                "searchreplace wordcount visualblocks visualchars code fullscreen",
                "insertdatetime media nonbreaking save table contextmenu directionality",
                "emoticons template paste textcolor"
            ],
            toolbar1: "undo redo | forecolor | bold italic | link",
            theme_advanced_styles : "Texto 1=texto;Texto 2=epb3;Texto 3=titulares",
            content_css : "<?= $GLOBALS["CONF"]["url"]["root"] ?>/admin/css/inc.content.forms.css",
            mode : "specific_textareas",
            forced_root_block : "",
            editor_selector : "mceEditor"
        });
    </script>
    <script type="text/javascript">
        function deletionConfirmDialog(id)
        {
            if (confirm('Are you sure you want to delete the content?')) {
                    location.replace("?action=deleteField&<?=$obj->_dbIndex?>=<?=$obj->getID()?>&contentID="+id);
            } else {
                // Do nothing!
            }
        };
    </script>
    <style>
    .left{
        float:left;
    }
    .right{
        float:right;
    }
    .end{
        clear:both;
    }
    </style>
</head>
<body>
  <?
    if($messenger)
    {
        $messages = $messenger->getArMessages();
        if(count($messages))
        {
            $html='<div id="respuesta_estado_orden" class="alert alert-success fade in"><div class="left">';
            foreach($messages as $key => $value)
            {
                $html.=$value."<br>";
            }
            $html.='</div>
                        <div class="right">
                            <button class="btn_close_messeger close" data-dismiss="alert" type="button">×</button>
                        </div>
                        <div class="end"></div>
                    </div>';
        }
        echo $html;
    }
    ?>
    <section id="content">
        <section class="main padder">
            <div class="row">
                <br>
                <!-- .breadcrumb -->
                <ul class="breadcrumb">
                    <li><a href="."><?= $module->name ?></a></li>
                    <li><a href="abm.php?<?=$obj->_dbIndex."=".$obj->getID()?>"><?= $obj->name ?></a></li> 
                    <li class="active">Aditional Data</li>
                </ul>
                <div class="col-sm-12">
                    <section class="panel">
                        <div class="panel-body">
                            <form action="" method="post" enctype="multipart/form-data" class="form-horizontal">
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Field</label>
                                    <div class="col-lg-8">
                                        <input type="text" name="field_name" placeholder="Name" class="form-control" value="">
                                    </div>
                                </div>
                                <div class="form-group">
                                    <label class="col-lg-3 control-label">Information</label>
                                    <div class="col-lg-8">
                                        <textarea placeholder="Value" rows="5" class="form-control mceEditor" name="field_value"></textarea>
                                    </div>
                                </div>
                                <div class="form-group">
                                    <div class="col-lg-9 col-lg-offset-3">
                                        <button type="submit" class="btn btn-primary">Save</button> o 
                                        <a href="."><span> [Cancel]</span></a>
                                    </div>
                                </div>
                                <input type="hidden" name="action" value="saveField">
                            </form>
                            <div class="tableHeader"><strong>Additional Data Table</strong></div><br>
                                <div id="respuesta_estado_orden" class="hidden alert fade in">
                                    <div class="left">
                                        <div id="data_resp_ajax_order"></div>
                                    </div>
                                    <div class="right">
                                        <button class="btn_close_messeger close" data-dismiss="alert" type="button">×</button>
                                    </div>
                                    <div class="end"></div>
                                </div>
                                <table class="table table-striped b-t text-small">
                                    <thead>
                                        <th class="th-sortable" data-toggle="class">FieldID</th>
                                        <th class="th-sortable">Field</th>
                                        <th  class="th-sortable" style="width:122px;">Value</th>
                                        <th nowrap="nowrap" class="TableTitles" style="width: 35px; padding:0px 4px;">&nbsp;</th>
                                    </thead>
                                    <tbody class="data_fields">
                                        <?
                                        $sql = "SELECT * FROM `fort_capital_portfolio_table_fields` WHERE portfolioID=".$obj->getID()." ORDER BY  position";
                                        $res = mysql_query($sql, $dbLink); 
                                        while($row = mysql_fetch_array($res))
                                        {
                                            ?>
                                                <tr class="rowClickable" order-content="content_<?= $row['contentID'] ?>">
                                                    <td class="Number" onClick="" style="width:68px;"><?= $row['contentID'] ?></td>
                                                    <td><?= $row['field_name'] ?></td>
                                                    <td class="Active" style="width:122px;"><?= $row['field_value'] ?></td>
                                                    <td class="LastColumn" align="center" style="cursor: default;width: 35px; padding:0px 4px;"><a class="btn btn-danger" title="Eliminar" href="javascript:deletionConfirmDialog(<?=$row['contentID']?>)"><i class="icon-trash"></i></a></td>
                                                </tr>
                                            <?
                                        }
                                        ?>
                                    </tbody>
                                </table>
                                <!--<div class="well m-t">
                                    <div class="row">
                                        <div class="col-xs-12">
                                            <strong>Info de sistema </strong><br>
                                            <?= $module->unit ?> id: <?= $obj->getID() ?><br>
                                        </div>
                                        <div class="col-xs-6">
                                            Fecha de creaci&oacute;n : <?= $obj->date_created ?><br>
                                            Fecha &uacute;ltimo cambio: <?= $obj->date_modified ?></br>
                                        </div>
                                        <div class="col-xs-6">
                                            Usuario que cre&oacute;: <?= $obj->userCreated ?></br>
                                            Usuario que modific&oacute;: <?= $obj->userModified ?></br>
                                        </div>
                                    </div>
                                </div>-->
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </section>
    </section>
    <script>
    $j(".data_fields").sortable({revert: true, item:"tr",
        update: function(event, ui) {
            var finish_order_photo = "";
            var id_photo = $j(".data_fields").sortable("toArray",{attribute: 'order-content'});
            var i = 0;
            var n = id_photo.length;
            for(i;i<n;i++){
                finish_order_photo += "mySortable[]="+id_photo[i];
                if(i<(n-1)){
                    finish_order_photo += "&";
                }
            }
            $j.ajax({
                type:"POST",
                url: "?<?=$obj->_dbIndex."=".$obj->getID()?>",
                data:{newOrder:finish_order_photo, action:'orderContent'},
                success:function(res){
                    $j("#respuesta_estado_orden").css({"display":"none"});
                    $j("#respuesta_estado_orden").fadeIn("fast");
                    $j("#respuesta_estado_orden").removeClass("hidden");
                    var data = $j.parseJSON(res);
                    if(data["success"]==true){
                        $j("#data_resp_ajax_order").html(data["messages"]);
                        $j("#respuesta_estado_orden").addClass("alert-success");
                    }else{
                        $j("#data_resp_ajax_order").html(data["messages"]);
                        $j("#respuesta_estado_orden").addClass("alert-error");
                    }
                }
            });
        }});
    $j(".btn_close_messeger").click(function(){
        $j("#respuesta_estado_orden").fadeOut("fast");
    });
    
    $j(".data_fields").disableSelection();
    </script>
</body>
</html>
